package org.custom.spring.boot.security.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl;
import org.springframework.security.config.core.GrantedAuthorityDefaults;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import static org.cleaver.basic.constant.CleaverConstant.EMPTY;

/**
 * Spring-Security相关配置
 *
 * @author LiKun
 * @date 2021/11/11 13:57
 */
@Configuration
public class SecurityConfig {

    /**
     * 注册 Security 的加密策略
     *
     * @return BCryptPasswordEncoder
     */
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder(5);
    }

    /**
     * 去除security自定义的角色名称前缀 'ROLE_'
     *
     * @return GrantedAuthorityDefaults
     */
    @Bean
    public GrantedAuthorityDefaults grantedAuthorityDefaults() {
        return new GrantedAuthorityDefaults(EMPTY);
    }

    /**
     * spring-security角色间继承
     *
     * @return 角色间继承链
     */
    @Bean
    public RoleHierarchy roleHierarchy() {
        RoleHierarchyImpl hierarchy = new RoleHierarchyImpl();
        hierarchy.setHierarchy("ADMIN > USER \n USER > ANONYMOUS");

        return hierarchy;
    }

}
